import 'dart:ui';

import 'package:airbnb_clone/models/user.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import '../../../components/chat_user_lists.dart';

import '../../../components/dialog/msg_dialog.dart';
import '../../../constant/constant.dart';
import '../../../internal/http/dao/friend_list_dao.dart';
import '../../../internal/login_check/login_check.dart';
import '../../../models/response.dart';

class ChatScreen extends StatefulWidget {
  const ChatScreen({super.key});

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final List<User> _chatList = [];
  bool _isLogin = true;
  int page = 0;
  final ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    if (!LoginCheck.check()) {
      _isLogin = false;
    } else {
      _loadFriendListData();
    }
  }

  // 滑动事件监听
  void addPageListener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        setState(() {
          setState(() {
            page++;
            _loadFriendListData();
          });
        });
      }
      if (_scrollController.position.pixels ==
          _scrollController.position.minScrollExtent) {
        // print("scroll to top");
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // final textTheme = Theme.of(context).textTheme;
    final size = MediaQuery.sizeOf(context);
    return SizedBox(
      height: size.height,
      child: Stack(
        children: [
          SizedBox(
            height: size.height * 0.13,
            child: chatSreachInput(context),
          ),
          !_isLogin
              ? needLoginWidget(context)
              : Positioned.fill(
                  top: size.height * 0.13,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: bgGradientColor,
                      ),
                    ),
                    // 用户列表
                    child: ChatUserLists(
                      listData: _chatList,
                      scrollController: _scrollController,
                    ),
                  ))
        ],
      ),
    );
  }

  // 文章搜索
  SizedBox chatSreachInput(BuildContext context) {
    return SizedBox(
      height: 70,
      child: Stack(
        children: [
          ClipRect(
            child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40),
                child: Container(
                  padding: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: topBarBgColor,
                    ),
                  ),
                )),
          ),
          Positioned(
            left: 16.0,
            top: 50.0,
            child: GestureDetector(
              onTap: () => context.pushNamed('booking-details'),
              child: Hero(
                tag: 'planning',
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      width: 300,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16.0,
                        vertical: 8.0,
                      ),
                      decoration: BoxDecoration(
                        color: appWhite,
                        border: Border.all(color: appGrey, width: 1.0),
                        borderRadius: BorderRadius.circular(32.0),
                        boxShadow: [
                          BoxShadow(
                            color: const Color.fromARGB(255, 7, 7, 7)
                                .withOpacity(0.4),
                            blurRadius: 3.0,
                            spreadRadius: 0.0,
                            offset: const Offset(2, 2.0),
                          )
                        ],
                      ),
                      child: Row(
                        children: [
                          const Icon(Icons.search),
                          const SizedBox(width: 8.0),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'Search Users',
                                style: Theme.of(context)
                                    .textTheme
                                    .bodyMedium!
                                    .copyWith(fontWeight: FontWeight.bold),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    IconButton(
                      onPressed: () {},
                      style: IconButton.styleFrom(
                        backgroundColor: Colors.grey[200],
                        shape: const CircleBorder(

                            // side: BorderSide(color: Colors.black, width: 0),
                            ),
                      ),
                      icon: const Icon(
                        Icons.add,
                        color: Colors.black,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 需要登录的页面
  Widget needLoginWidget(BuildContext context) {
    return GestureDetector(
      child: Center(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
          child: Container(
            height: 195,
            width: 300,
            padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(20)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "用户未登录",
                  style: titleTextStyle,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextButton(
                      onPressed: () {
                        context.pushNamed("login");
                      },
                      style: normalButtonStyle,
                      child: Text(
                        "点击登录",
                        style: normalTextStyle,
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 加载用户列表数据
  Future<void> _loadFriendListData() async {
    TiebaResponse response = await FriendListDao.get(page);
    if (response.code == 200) {
      for (var userE in response.result["list"]) {
        if (mounted) {
          setState(() {
            _chatList.add(User(
                id: userE["friend_id"],
                userName: userE["friend_name"],
                userImg: "userImg",
                createTime: DateTime.parse(userE["create_time"])));
          });
        }
      }
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }
}
